package com.dq.utils;

import com.xiaoleilu.hutool.date.DateUtil;
import org.apache.commons.lang3.RandomStringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 随机函数工具类
 */

public class RandomUtil {
    static final char[] chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    static final char[] numbers = "0123456789".toCharArray();
    static final Random random = new Random();

    private static char get() {
        return chars[random.nextInt(chars.length)];
    }

    private static char getN() {
        return chars[random.nextInt(numbers.length)];
    }

    private static char[] get(int length) {
        char[] r = new char[length];
        for (int i = 0; i < length; i++) {
            r[i] = get();
        }
        return r;
    }

    private static char[] getN(int length) {
        char[] r = new char[length];
        for (int i = 0; i < length; i++) {
            r[i] = getN();
        }
        return r;
    }

    public static String getString(int length) {
        return String.valueOf(get(length));
    }

    public static String getNumber(int length) { // 0103656422 // 前导"0"会保留
        return String.valueOf(getN(length));
    }

    /**
     * 生成订单号
     * yyyyMMddHHmmss 6位随机  4位用户id
     * @return
     */
    public static String getGenerateOrderNo(Long userId){
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StringBuffer stringBuffer = new StringBuffer(userId.toString());
        //id长度大于4  取后四位
        if(stringBuffer.length()>4){
            stringBuffer = new StringBuffer(stringBuffer.substring(stringBuffer.length()-4,stringBuffer.length()));
        }
        //长度小于4  补全4位
        while (stringBuffer.length()<4){
            stringBuffer.insert(0,"0");
        }
        return time+RandomUtil.getNumber(6)+stringBuffer.toString();
    }
}
